const router=require('koa-router')();
const events=require('events');
const _=require('underscore');
const config=require('../config/config');
const {User}=require('../models/index');
const authRedis=require('../models/auth.redis.server.model');
const Auth=require('../models/auth.server.model');


//获取用户详情
router.get('/user/profile',async ctx=>{
    let {access_token:token}=ctx.query,ee=new events;
    ee.on('fail',msg=>{
        console.log('/user/profile fail:',msg);
        ctx.body={
            code:401,
            error:msg
        };
    });

    let auth=await Auth.findOne({token});
    if(!auth)return ee.emit('fail','Token错误');

    let redisToken=await authRedis.findToken({client_id:auth.client_id,token});//通过查询redis,判断token是否已经过期
    if(!redisToken){
        return ctx.body={
            code:204,
            msg:'请使用refresh_token刷新授权令牌'
        };
    }

    let user=await User.findOne({_id:auth.user});
    let data=_.pick(user,'_id','name','email');
    data.avatar=`localhost:${config.port}/uploads/${user.avatar}`;
    ctx.body={
        code:200,
        data
    };
});

module.exports=router;